package com.waqu.common.utils.http;

import java.io.IOException;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.waqu.common.utils.collection.ArrayMapTools;
import com.waqu.common.utils.text.StringTools;

/**
 * @Title ConnectGet.java
 * @Package com.waqu.common.utils.http
 * @author Administrator
 * @date 2015年5月25日 下午12:55:25
 * @version V1.0
 */
class ConnectSSLGet {

	public static String send(String url, Map<String, String> params, String charsetName)
			throws ClientProtocolException, IOException, GeneralSecurityException {
		CloseableHttpClient closeableHttpClient = ConnectTools.createSSLInsecureClient();
		String result = null;
		try {
			StringBuffer strParams = new StringBuffer();
			List<NameValuePair> parameters = new ArrayList<>();
			if (ArrayMapTools.isNotEmpty(params)) {
				for (Entry<String, String> entry : params.entrySet()) {
					parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
				}
			}

			if (StringTools.isNotEmpty(strParams.toString()))
				url += (url.indexOf("?") > 0 ? "&" : "?")
						+ EntityUtils.toString(new UrlEncodedFormEntity(parameters, charsetName));

			HttpGet sslGet = new HttpGet(url);
			sslGet.setHeader("accept", "*/*");
			sslGet.setHeader("connection", "keep-alive");
			sslGet.setHeader("user-agent",
					"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0");

			HttpResponse response = closeableHttpClient.execute(sslGet);
			if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode() && null != response.getEntity()) {
				String charset = ConnectTools.getCharsetFromResponse(response);
				charsetName = StringTools.isNotEmpty(charset) ? charset : charsetName;
				result = EntityUtils.toString(response.getEntity(), Charset.forName(charsetName));
			}
		} finally {
			closeableHttpClient.close();
		}

		return result;
	}

}
